<template>
  <div>
    <h3>HellowWorld组件：演示组合API基本用法</h3>
    <p>setup组合API的三种写法</p>

    name:<input type="text" v-model="states.formObj.name" /> age:<input
      type="text"
      v-model="states.formObj.age"
    />
    <hr />
    <ul>
      <li
        v-for="item in states.list"
        :key="item.name"
        @click="remove(item.name)"
      >
        {{ item.name + '-' + item.age }}
      </li>
    </ul>
    <hr />
    <button @click="addItem">点击增加list</button><br />
    <button @click="changeCount">调用方法改变count: {{ count }}</button><br />
    <button @click="count++">通过count++自增改变: {{ count }}</button><br />
  </div>
</template>

<script>
import { reactive, ref } from 'vue'
//写法3: 所有变量统一在外部js的函数里声明并导入，在setup里调用该函数并return，类似方法二
// import useModule from './hello-world/use-module'
export default {
  name: 'HelloWorld',
  setup(props, context) {
    console.log('setup钩子执行')
    //setup为组合API的入口函数
    //写法1：所有的变量在setup方法里面声明再return出去
    let count = ref(5) //定义初值通过ref监听数据变化，可见听基本数据类型和复杂数据类型，一般用于基本数据类型的监听
    //定义初值通过reactive监听数据变化，一般用于复杂数据的监听
    let states = reactive({
      formObj: {
        name: '',
        age: '',
      },
      list: [
        { name: 'zqf', age: 12 },
        { name: 'wangwu', age: 13 },
        { name: 'lisi', age: 14 },
      ],
    })
    function remove(name) {
      states.list = states.list.filter((item) => item.name !== name)
    }
    function addItem() {
      let { name, age } = states.formObj
      if (!name || !age) {
        alert('请完善表单')
        return false
      }
      states.list.push({ name, age })
      states.formObj = { name: '', age: '' }
    }
    function changeCount() {
      count.value = count.value + 1
    }
    // let {count, states, remove, addItem, changeCount} = useModule()
    //let {count, states, remove, addItem, changeCount} = currentModule()
    //组合API定义的方法和变量必须通过return暴露出去
    return { count, states, remove, addItem, changeCount }
  },
  data() {
    return {
      user: {
        name: 'zqf',
      },
    }
  },
  beforeCreate() {
    console.log('before-create钩子执行')
  },
  mounted() {
    console.log(this.user)
  },
}
//写法2:所有变量统一在外部函数里声明，在setup里调用该函数并return
/* function currentModule (){
	let count = ref(5)
	let states = reactive({
		formObj: {
			name: '',
			age: '',
		},
		list: [
			{name: 'zqf', age: 12},
			{name: 'wangwu', age: 13},
			{name: 'lisi', age: 14},

		]
	})
	function remove(name){
		states.list = states.list.filter(item => item.name !== name)
	}
	function addItem(){
		let {name, age} = states.formObj
		states.list.push({name, age})
		states.formObj = {name: '', age: ''}
	}
	function changeCount() {
		console.log(count)
		count.value = count.value+1
	}
	return {count, states, remove, addItem, changeCount}
} */
</script>
